/**    
 * @{#} DoctorAccountActivity.java Create on 2014年7月23日 下午1:14:55    
 *    
 * @author <a href="mailto:evan0502@qq.com">Evan</a>   
 * @version 1.0    
 */
package com.smiier.skin;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import cn.o.app.event.listener.OnSelectedChangeListener;
import cn.o.app.json.JsonUtil;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.ui.OActionSheet;
import cn.o.app.ui.OActionSheet.OActionItem;
import cn.o.app.ui.OActionSheet.OnActionItemClickListener;
import cn.o.app.ui.OTab;
import cn.o.app.ui.OTabItem;
import cn.skinapp.R;

import com.evan.common.adapter.BaseListAdapter;
import com.evan.common.pullrefresh.PullToRefreshBase;
import com.evan.common.pullrefresh.PullToRefreshBase.OnRefreshListener;
import com.evan.common.pullrefresh.PullToRefreshListView;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.net.AccountGetListTask;
import com.smiier.skin.net.AccountGetListTask.AccountGetListRequest;
import com.smiier.skin.net.AccountGetListTask.AccountGetListResponse;
import com.smiier.skin.net.AccountGetTask;
import com.smiier.skin.net.AccountGetTask.AccountGetRequest;
import com.smiier.skin.net.AccountGetTask.AccountGetResponse;
import com.smiier.skin.net.CostRechargeTask;
import com.smiier.skin.net.CostRechargeTask.CostRechargeItem;
import com.smiier.skin.net.CostRechargeTask.CostRechargeRequest;
import com.smiier.skin.net.CostRechargeTask.CostRechargeResponse;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.util.GlobalFormat;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;

@SuppressLint("InflateParams")
public class AccountActivity extends BasicActivity implements
		OnRefreshListener<ListView> {

	private TextView text_money;

	ArrayList<Object> chongzhiList = new ArrayList<Object>();
	// TextView text_empty;
	LayoutInflater inflater;
	private static final String mCost = "充值¥%s元";
	private static final String mFree = "(送¥%s元)";
	private RelativeLayout mRlAccountContainer;

	ArrayList<Object> mAccountRecordAll, mAccountRecordChongzhi,
			mAccountRecordZixun, mCurrentRecord;

	private PullToRefreshListView mListviewAccountRecord;

	AccountRecordAdapter adapter;

	View viewLineAll;

	View viewLineChongzhi;

	View viewLineZixun;

	Button mBtnChongzhi;
	String mStartId;
	protected Integer mType = null;// 列表类型
	private OTab mTab;
	private OTabItem mMoney1, mMoney2, mMoney3;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_account);

		text_money = (TextView) findViewById(R.id.text_money);
		mRlAccountContainer = (RelativeLayout) findViewById(R.id.rl_account_container);
		mListviewAccountRecord = (PullToRefreshListView) findViewById(R.id.listview_account_record);
		mBtnChongzhi = (Button) findViewById(R.id.btn_chongzhi);
		mTab = findViewById(R.id.tab, OTab.class);
		mMoney1 = findViewById(R.id.money_1, OTabItem.class);
		mMoney2 = findViewById(R.id.money_2, OTabItem.class);
		mMoney3 = findViewById(R.id.money_3, OTabItem.class);
		mTab.setOnSelectedChangeListener(new OnSelectedChangeListener() {

			@Override
			public void onChanged(View v, int index) {
				onSelected(v, index);
			}
		});
		;
		init();
		setNavTitle("我的账户");
		setNavRightBtn("交易密码");

		inflater = LayoutInflater.from(this);
		/*
		 * text_empty = (TextView) inflater .inflate(R.layout.include_no_data,
		 * null); text_empty.setText("暂无记录。");
		 * text_empty.setVisibility(View.VISIBLE);
		 */
		LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		layoutParams.topMargin = CommonUtility.dip2px(this, 20);
		layoutParams.bottomMargin = CommonUtility.dip2px(this, 20);
		// text_empty.setLayoutParams(layoutParams);

		// mRlAccountContainer.addView(text_empty, 0);

		if (CommonUtility.isDoctor()) {
			mMoney2.setText("提现");
			mMoney3.setText("解答");
			mBtnChongzhi.setText("提现");
		}

		mAccountRecordAll = new ArrayList<Object>();
		adapter = new AccountRecordAdapter(this, mAccountRecordAll);
		mListviewAccountRecord.setAdapter(adapter);
		mListviewAccountRecord.setOnRefreshListener(this);
		mListviewAccountRecord.setScrollLoadEnabled(true);

		loadRecord(mAccountRecordAll);

		IntentFilter filter = new IntentFilter(
				Constant.RECEIVER_ACCOUNT_CHONGZHI);
		registerReceiver(receiver, filter);
	}

	private void onSelected(View v, int index) {
		mStartId = null;
		if (index == 0) {
			if (mAccountRecordAll == null) {
				mAccountRecordAll = new ArrayList<Object>();
			}
			mType = null;
			mAccountRecordAll.clear();

			mCurrentRecord = mAccountRecordAll;
			loadRecord(mAccountRecordAll);

		} else if (index == 1) {
			if (mAccountRecordChongzhi != null) {
				mAccountRecordChongzhi.clear();
			}
			if (CommonUtility.isDoctor()) {
				mType = 1;
			} else {
				mType = 0;
			}
			if (CommonUtility.isNull(mAccountRecordChongzhi)) {
				mAccountRecordChongzhi = new ArrayList<Object>();
			}
			mCurrentRecord = mAccountRecordChongzhi;
			loadRecord(mAccountRecordChongzhi);
		} else if (index == 2) {
			if (mAccountRecordZixun != null) {
				mAccountRecordZixun.clear();
			}
			if (CommonUtility.isDoctor()) {
				mType = 3;
			} else {
				mType = 2;
			}
			if (CommonUtility.isNull(mAccountRecordZixun)) {
				mAccountRecordZixun = new ArrayList<Object>();

			}
			mCurrentRecord = mAccountRecordZixun;
			loadRecord(mAccountRecordZixun);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		// MobclickAgent.onResume(this);

		AccountGetRequest req = new AccountGetRequest();
		req.token = GlobalSettings.sToken;
		AccountGetTask task = new AccountGetTask();
		task.setRequest(req);
		task.addListener(new NetTaskListener<AccountGetTask.AccountGetRequest, AccountGetTask.AccountGetResponse>() {

			@Override
			public void onException(
					INetTask<AccountGetRequest, AccountGetResponse> task,
					Exception e) {

			}

			@Override
			public void onComplete(
					INetTask<AccountGetRequest, AccountGetResponse> task,
					AccountGetResponse response) {
				if (response.ResultCode != 200) {
					return;
				}
				GlobalSettings.sYue = response.Res;
				text_money.setText(GlobalFormat.formatCNY(GlobalSettings.sYue));
			}
		});
		add(task);
		if (mCurrentRecord != null) {
			mCurrentRecord.clear();
			loadRecord(mCurrentRecord);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		CommonUtility.unRegisteReciver(this, receiver);
	}

	public void onClick(View view) {
		int id = view.getId();
		if (id == R.id.btn_left) {
			finish();
		} else if (id == R.id.text_right) {
			Intent intent = null;
			try {
				if (CommonUtility.isNull(GlobalSettings.sUser.Mobile)) {
					intent = new Intent(getContext(),
							RegisterFirstStepActivity.class);
					intent.putExtra(Constant.IDENTITY_KEY_1,
							Constant.TYPE_UPDATE_MOBILE);
					startActivity(intent);
				} else {
					CommonUtility.confirmSendCode((Activity) getContext(),
							GlobalSettings.sUser.Mobile,
							Constant.TYPE_RESET_PAY_PASSWORD);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (id == R.id.btn_chongzhi) {
			if (CommonUtility.isDoctor()) {
				startActivity(new Intent(activity, TixianActivity.class));
			} else {
				if (GlobalSettings.mCostRecharge != null
						&& GlobalSettings.mCostRecharge.size() > 2) {
					showDialog(GlobalSettings.mCostRecharge);
				} else {
					CostRechargeTask task = new CostRechargeTask();
					CostRechargeRequest req = new CostRechargeRequest();
					task.addListener(new NetTaskListener<CostRechargeTask.CostRechargeRequest, CostRechargeTask.CostRechargeResponse>() {

						@Override
						public void onComplete(
								INetTask<CostRechargeRequest, CostRechargeResponse> task,
								CostRechargeResponse response) {
							if (response != null) {
								ArrayList<CostRechargeItem> arrays = response;
								if (arrays.size() > 0) {
									GlobalSettings.mCostRecharge = arrays;
									showDialog(arrays);
								}
							}
						}

						@Override
						public void onException(
								INetTask<CostRechargeRequest, CostRechargeResponse> task,
								Exception e) {

						}
					});
					task.setRequest(req);
					add(task);
				}
			}
		}
	}

	private void showDialog(final ArrayList<CostRechargeItem> arrays) {
		ArrayList<OActionItem> dataProvider = new ArrayList<OActionSheet.OActionItem>();
		OActionItem item = null;
		for (CostRechargeItem cost : arrays) {
			item = new OActionItem();
			item.setText(String.format(mCost, cost.Cost));
			if (cost.Gift > 0) {
				item.setmFree(String.format(mFree, cost.Gift));
				item.setmShow(true);
			} else {
				item.setmFree("");
				item.setmShow(false);
			}

			item.setTextColor(Color.BLACK);
			dataProvider.add(item);
		}
		OActionSheet<OActionItem> actionSheet = new OActionSheet<OActionSheet.OActionItem>(
				this);
		actionSheet.setTitle("充值就送礼，咨询更优惠");
		actionSheet.setIsCharge(true);
		actionSheet.setCancel("取消");
		actionSheet.setDataProvider(dataProvider);
		actionSheet
				.setOnActionItemClickListener(new OnActionItemClickListener<OActionSheet.OActionItem>() {

					@Override
					public void onItemClick(OActionSheet<OActionItem> sheet,
							View v, int position, OActionItem dataItem) {
						CostRechargeItem cost = arrays.get(position);
						if (CommonUtility.isDoctor()) {
							startActivity(new Intent(getContext(),
									TixianActivity.class));
						} else {
							Intent i = new Intent(getContext(),
									ChongzhiActivity.class);
							i.putExtra("Cost_Recharge", cost.Cost);
							startActivity(i);
						}

					}
				});
		actionSheet.show(true, true);
	}

	private void operateData(ArrayList<Object> list) {
		adapter.notifyUpdate(list);
		/*
		 * if (list.size() > 0) { text_empty.setVisibility(View.GONE); } else {
		 * text_empty.setVisibility(View.VISIBLE); }
		 */
		if (list.size() < 1) {
			mListviewAccountRecord.setContextEmptyType(true, 2);
		} else {
			mListviewAccountRecord.setContextEmptyType(false, 2);
		}
	}

	void loadRecord(final ArrayList<Object> list) {
		AccountGetListRequest req = new AccountGetListRequest();
		req.pagesize = GlobalSettings.PAGE_SIZE;
		req.token = GlobalSettings.sToken;
		req.startid = mStartId;
		req.type = mType;
		AccountGetListTask task = new AccountGetListTask();
		task.setRequest(req);
		task.addListener(new NetTaskListener<AccountGetListTask.AccountGetListRequest, AccountGetListTask.AccountGetListResponse>() {
			@Override
			public void onException(
					INetTask<AccountGetListRequest, AccountGetListResponse> task,
					Exception e) {
				mListviewAccountRecord.doComplete();
				mListviewAccountRecord.setContextEmptyType(true, 2);
			}

			@Override
			public void onComplete(
					INetTask<AccountGetListRequest, AccountGetListResponse> task,
					AccountGetListResponse response) {
				mListviewAccountRecord.doComplete();

				if (response.ResultCode != 200) {
					mListviewAccountRecord.setContextEmptyType(true, 2);
					return;
				}
				try {
					JSONArray array = new JSONArray(JsonUtil
							.convert(response.Res.AccountList));
					CommonUtility.putAll(list, array, true);
					if (array.length() > 0) {
						mStartId = ((JSONObject) array.get(array.length() - 1))
								.getString("id");
					}
					operateData(list);

				} catch (Exception e) {
					e.printStackTrace();
					mListviewAccountRecord.setContextEmptyType(true, 2);
				}
			}
		});
		add(task);
	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			mAccountRecordAll = null;

		}
	};

	@SuppressLint("InflateParams")
	public static class AccountRecordAdapter extends BaseListAdapter {

		/**
		 * @param activity
		 * @param list
		 */
		public AccountRecordAdapter(Activity activity, ArrayList<?> list) {
			super(activity, list);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (CommonUtility.isNull(convertView)) {
				convertView = inflater
						.inflate(R.layout.item_money_record, null);
				holder = new ViewHolder();
				holder.textMoney = (TextView) convertView
						.findViewById(R.id.text_money);
				holder.textDate = (TextView) convertView
						.findViewById(R.id.text_date);
				holder.textOperate = (TextView) convertView
						.findViewById(R.id.text_operate);
				CommonUtility.setViewHolderTag(convertView, holder);
			} else {
				holder = (ViewHolder) CommonUtility
						.getViewHolderTag(convertView);
			}

			JSONObject ooo = (JSONObject) getItem(position);
			try {

				String str = CommonUtility.formatDate(
						ooo.getString("CreateTime"), 0, 16);
				holder.textDate.setText(str + "，"
						+ (ooo.getInt("Type") == 0 ? "充值" : "咨询"));
				int type = ooo.getInt("Type");
				int status = ooo.getInt("Status");
				if (type == 0) {
					holder.textMoney.setText("+" + ooo.getString("Cost") + "元");
					if (status == 1) {
						holder.textMoney.setTextColor(0xfff9a54a);
						holder.textOperate.setTextColor(0xfff9a54a);
						holder.textOperate.setText("处理中");
					} else if (status == 2) {
						holder.textMoney.setTextColor(0xff53AEA3);
						holder.textOperate.setTextColor(0xff53AEA3);
						holder.textOperate.setText("已完成");
					} else {
						holder.textMoney.setTextColor(0xffF4A520);
						holder.textOperate.setTextColor(0xffF4A520);
						holder.textOperate.setText("处理中");
					}

				} else if (type == 2) {
					holder.textMoney.setText("-" + ooo.getString("Cost") + "元");
					holder.textMoney.setTextColor(0xff618CE0);
					holder.textOperate.setTextColor(0xff618CE0);
					holder.textOperate.setText("已完成");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}

		class ViewHolder {
			TextView textMoney, textDate, textOperate;
		}
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

	}

	@Override
	public void onPullUpToLoadMore(PullToRefreshBase<ListView> refreshView) {
		if (mType == null) {
			loadRecord(mAccountRecordAll);
		} else if (mType == 0) {
			loadRecord(mAccountRecordChongzhi);
		} else {
			loadRecord(mAccountRecordZixun);
		}
	}

	/*
	 * @Override public void onPause() { super.onPause();
	 * MobclickAgent.onPause(getContext()); }
	 */

}
